/*  ----------------------------------------------------------------------------
 *  Arello Mobile
 *  Fast 3d Engine
 *  ----------------------------------------------------------------------------
 * Except where otherwise noted, this work is licensed under
 * http://creativecommons.org/licenses/by/3.0
 */

#include <Config.h>
#include "Soul.h"
#include <Gluck.h>
							
namespace liba {
namespace animate {

bool registration_disabled = false; 
typedef std::list<Soul *> Souls;
	
static Souls * souls      = 0;
static Souls * dead_souls = 0;
	
Soul::Creator::Creator()
{
	if( souls )
		THROW(Gluck(__FUNCTION__, "Souls already created"));
	
	souls      = new Souls;
	dead_souls = new Souls;
}

Soul::Creator::~Creator()
{
	delete souls; souls = 0;
}

void Soul::Creator::disable_registration()
{
	registration_disabled = true;
}

void Soul::Creator::enable_registration()
{
	registration_disabled = false;
}

void Soul::Creator::LifeCycle(time_float delta_time)
{
	// send life_cycle to all souls
	Souls::iterator it = souls->begin();
	for( ; it != souls->end(); ++it )
		(*it)->LifeCycle( delta_time );
	
	// remove dead souls
	it = dead_souls->begin();
	for( ; it != dead_souls->end(); ++it )
		delete *it;
	
	dead_souls->clear();
}


Soul::Soul()
:	active_soul(false)
{
	if(registration_disabled)
		return;

	active_soul = true;
	souls->push_back( this );
}

Soul::Soul(const Soul & other)
{
	active_soul = true;
	souls->push_back( this );
}

Soul::~Soul()
{
	if(active_soul)
		souls->remove( this );
}

void Soul::mark_as_dead()
{
	dead_souls->push_back(this);
}
	
void Soul::activate_soul(bool activate)
{
	if(activate && !active_soul)
	{
		souls->push_back(this);
	}
	if(!activate && active_soul)
	{
		souls->remove(this);
	}
	active_soul = activate;
}

} // namespace animate
} // namespace liba

